// 统一配置管理
import dotenv from 'dotenv';
import path from 'path';
import { fileURLToPath } from 'url';

// 确保从项目根目录加载环境变量
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const projectRoot = path.resolve(__dirname, '..');

dotenv.config({ path: path.join(projectRoot, '.env') });

const config = {
  // 应用配置
  app: {
    name: process.env.APP_NAME || 'fullstack-nodejs-app',
    version: process.env.APP_VERSION || '1.0.0',
    environment: process.env.NODE_ENV || 'development',
    logLevel: process.env.LOG_LEVEL || 'info'
  },

  // 服务器配置
  servers: {
    backend: {
      port: parseInt(process.env.BACKEND_PORT) || 3000,
      host: process.env.BACKEND_HOST || 'localhost'
    },
    frontend: {
      port: parseInt(process.env.FRONTEND_PORT) || 8080,
      host: process.env.FRONTEND_HOST || 'localhost'
    },
    userClient: {
      port: parseInt(process.env.USER_CLIENT_PORT) || 3001,
      host: process.env.USER_CLIENT_HOST || 'localhost'
    }
  },

  // 数据库配置
  database: {
    postgresql: {
      host: process.env.DB_HOST || 'localhost',
      port: parseInt(process.env.DB_PORT) || 5432,
      name: process.env.DB_NAME || 'bike_wholesale',
      user: process.env.DB_USER || 'postgres',
      password: process.env.DB_PASSWORD || 'password',
      maxConnections: parseInt(process.env.DB_MAX_CONNECTIONS) || 20,
      idleTimeout: parseInt(process.env.DB_IDLE_TIMEOUT) || 30000,
      connectionTimeout: parseInt(process.env.DB_CONNECTION_TIMEOUT) || 2000
    },
    redis: {
      host: process.env.REDIS_HOST || 'localhost',
      port: parseInt(process.env.REDIS_PORT) || 6379,
      password: process.env.REDIS_PASSWORD || '',
      db: parseInt(process.env.REDIS_DB) || 0,
      keyPrefix: process.env.REDIS_KEY_PREFIX || 'bike:'
    },
    mongodb: {
      uri: process.env.MONGODB_URI || 'mongodb://localhost:27017/bike_community',
      db: process.env.MONGODB_DB || 'bike_community',
      poolSize: parseInt(process.env.MONGODB_POOL_SIZE) || 10
    }
  },

  // 安全配置
  security: {
    jwt: {
      secret: process.env.JWT_SECRET || 'your-super-secret-jwt-key',
      expiresIn: process.env.JWT_EXPIRES_IN || '7d',
      issuer: process.env.JWT_ISSUER || 'fullstack-app'
    },
    cors: {
      allowedOrigins: process.env.ALLOWED_ORIGINS?.split(',') || [
        'http://localhost:8080',
        'http://localhost:3001'
      ]
    },
    rateLimit: {
      windowMs: parseInt(process.env.RATE_LIMIT_WINDOW_MS) || 15 * 60 * 1000,
      maxRequests: parseInt(process.env.RATE_LIMIT_MAX_REQUESTS) || 100
    }
  },

  // 性能配置
  performance: {
    compression: {
      threshold: parseInt(process.env.COMPRESSION_THRESHOLD) || 1024
    },
    cache: {
      ttl: parseInt(process.env.CACHE_TTL) || 3600, // 1小时
      maxSize: parseInt(process.env.CACHE_MAX_SIZE) || 1000
    }
  },

  // 监控配置
  monitoring: {
    enabled: process.env.MONITORING_ENABLED === 'true',
    metricsPort: parseInt(process.env.METRICS_PORT) || 9090,
    healthCheckInterval: parseInt(process.env.HEALTH_CHECK_INTERVAL) || 30000
  }
};

// 验证必需的环境变量
const requiredEnvVars = ['JWT_SECRET'];
if (config.app.environment === 'production') {
  requiredEnvVars.push('DB_HOST', 'DB_NAME', 'DB_USER', 'DB_PASSWORD');
}

requiredEnvVars.forEach(envVar => {
  if (!process.env[envVar] && config.app.environment === 'production') {
    console.warn(`⚠️ 警告: 生产环境缺少必需的环境变量 ${envVar}`);
  }
});

export default config;